3 * A codec for MediaWiki page titles.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Daniel Kinzler
23 use MediaWiki\Interwiki\InterwikiLookup
;
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Linker\LinkTarget
;
28 * A codec for MediaWiki page titles.
30 * @note Normalization and validation is applied while parsing, not when formatting.
31 * It's possible to construct a TitleValue with an invalid title, and use MediaWikiTitleCodec
32 * to generate an (invalid) title string from it. TitleValues should be constructed only
33 * via parseTitle() or from a (semi)trusted source, such as the database.
35 * @see https://www.mediawiki.org/wiki/Requests_for_comment/TitleValue
38 class MediaWikiTitleCodec
implements TitleFormatter
, TitleParser
{
47 protected $genderCache;
52 protected $localInterwikis;
55 * @var InterwikiLookup
57 protected $interwikiLookup;
65 * @param Language $language The language object to use for localizing namespace names.
66 * @param GenderCache $genderCache The gender cache for generating gendered namespace names
67 * @param string[]|string $localInterwikis
68 * @param InterwikiLookup|null $interwikiLookup
69 * @param NamespaceInfo|null $nsInfo
71 public function __construct( Language
$language, GenderCache
$genderCache,
72 $localInterwikis = [], InterwikiLookup
$interwikiLookup = null,
73 NamespaceInfo
$nsInfo = null
75 if ( !$interwikiLookup ) {
76 wfDeprecated( __METHOD__
. ' with no InterwikiLookup argument', '1.34' );
77 $interwikiLookup = MediaWikiServices
::getInstance()->getInterwikiLookup();
80 wfDeprecated( __METHOD__
. ' with no NamespaceInfo argument', '1.34' );
81 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
83 $this->language
= $language;
84 $this->genderCache
= $genderCache;
85 $this->localInterwikis
= (array)$localInterwikis;
86 $this->interwikiLookup
= $interwikiLookup;
87 $this->nsInfo
= $nsInfo;
91 * @see TitleFormatter::getNamespaceName()
93 * @param int $namespace
96 * @throws InvalidArgumentException If the namespace is invalid
97 * @return string Namespace name with underscores (not spaces)
99 public function getNamespaceName( $namespace, $text ) {
100 if ( $this->language
->needsGenderDistinction() &&
101 $this->nsInfo
->hasGenderDistinction( $namespace )
103 // NOTE: we are assuming here that the title text is a user name!
104 $gender = $this->genderCache
->getGenderOf( $text, __METHOD__
);
105 $name = $this->language
->getGenderNsText( $namespace, $gender );
107 $name = $this->language
->getNsText( $namespace );
110 if ( $name === false ) {
111 throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
118 * @see TitleFormatter::formatTitle()
120 * @param int|bool $namespace The namespace ID (or false, if the namespace should be ignored)
121 * @param string $text The page title. Should be valid. Only minimal normalization is applied.
122 * Underscores will be replaced.
123 * @param string $fragment The fragment name (may be empty).
124 * @param string $interwiki The interwiki name (may be empty).
126 * @throws InvalidArgumentException If the namespace is invalid
129 public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
131 if ( $interwiki !== '' ) {
132 $out = $interwiki . ':';
135 if ( $namespace != 0 ) {
137 $nsName = $this->getNamespaceName( $namespace, $text );
138 } catch ( InvalidArgumentException
$e ) {
139 // See T165149. Awkward, but better than erroneously linking to the main namespace.
140 $nsName = $this->language
->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$namespace}";
143 $out .= $nsName . ':';
147 if ( $fragment !== '' ) {
148 $out .= '#' . $fragment;
151 $out = str_replace( '_', ' ', $out );
157 * Parses the given text and constructs a TitleValue.
159 * @param string $text The text to parse
160 * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
162 * @throws MalformedTitleException
165 public function parseTitle( $text, $defaultNamespace = NS_MAIN
) {
166 // Convert things like é ā or 〗 into normalized (T16952) text
167 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
169 // NOTE: this is an ugly cludge that allows this class to share the
170 // code for parsing with the old Title class. The parser code should
171 // be refactored to avoid this.
172 $parts = $this->splitTitleString( $filteredText, $defaultNamespace );
174 // Fragment-only is okay, but only with no namespace
175 if ( $parts['dbkey'] === '' &&
176 ( $parts['fragment'] === '' ||
$parts['namespace'] !== NS_MAIN
) ) {
177 throw new MalformedTitleException( 'title-invalid-empty', $text );
180 return new TitleValue(
189 * Given a namespace and title, return a TitleValue if valid, or null if invalid.
191 * @param int $namespace
192 * @param string $text
193 * @param string $fragment
194 * @param string $interwiki
196 * @return TitleValue|null
198 public function makeTitleValueSafe( $namespace, $text, $fragment = '', $interwiki = '' ) {
199 if ( !$this->nsInfo
->exists( $namespace ) ) {
203 $canonicalNs = $this->nsInfo
->getCanonicalName( $namespace );
204 $fullText = $canonicalNs == '' ?
$text : "$canonicalNs:$text";
205 if ( strval( $interwiki ) != '' ) {
206 $fullText = "$interwiki:$fullText";
208 if ( strval( $fragment ) != '' ) {
209 $fullText .= '#' . $fragment;
213 $parts = $this->splitTitleString( $fullText );
214 } catch ( MalformedTitleException
$e ) {
218 return new TitleValue(
219 $parts['namespace'], $parts['dbkey'], $parts['fragment'], $parts['interwiki'] );
223 * @see TitleFormatter::getText()
225 * @param LinkTarget $title
227 * @return string $title->getText()
229 public function getText( LinkTarget
$title ) {
230 return $title->getText();
234 * @see TitleFormatter::getText()
236 * @param LinkTarget $title
240 public function getPrefixedText( LinkTarget
$title ) {
241 if ( !isset( $title->prefixedText
) ) {
242 $title->prefixedText
= $this->formatTitle(
243 $title->getNamespace(),
246 $title->getInterwiki()
250 return $title->prefixedText
;
255 * @see TitleFormatter::getPrefixedDBkey()
256 * @param LinkTarget $target
259 public function getPrefixedDBkey( LinkTarget
$target ) {
260 return strtr( $this->formatTitle(
261 $target->getNamespace(),
264 $target->getInterwiki()
269 * @see TitleFormatter::getText()
271 * @param LinkTarget $title
275 public function getFullText( LinkTarget
$title ) {
276 return $this->formatTitle(
277 $title->getNamespace(),
279 $title->getFragment(),
280 $title->getInterwiki()
285 * Normalizes and splits a title string.
287 * This function removes illegal characters, splits off the interwiki and
288 * namespace prefixes, sets the other forms, and canonicalizes
291 * @todo this method is only exposed as a temporary measure to ease refactoring.
292 * It was copied with minimal changes from Title::secureAndSplit().
294 * @todo This method should be split up and an appropriate interface
295 * defined for use by the Title class.
297 * @param string $text
298 * @param int $defaultNamespace
300 * @throws MalformedTitleException If $text is not a valid title string.
301 * @return array A map with the fields 'interwiki', 'fragment', 'namespace',
302 * 'user_case_dbkey', and 'dbkey'.
304 public function splitTitleString( $text, $defaultNamespace = NS_MAIN
) {
305 $dbkey = str_replace( ' ', '_', $text );
310 'local_interwiki' => false,
312 'namespace' => $defaultNamespace,
314 'user_case_dbkey' => $dbkey,
317 # Strip Unicode bidi override characters.
318 # Sometimes they slip into cut-n-pasted page titles, where the
319 # override chars get included in list displays.
320 $dbkey = preg_replace( '/[\x{200E}\x{200F}\x{202A}-\x{202E}]+/u', '', $dbkey );
322 # Clean up whitespace
323 # Note: use of the /u option on preg_replace here will cause
324 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
325 # conveniently disabling them.
326 $dbkey = preg_replace(
327 '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
331 $dbkey = trim( $dbkey, '_' );
333 if ( strpos( $dbkey, UtfNormal\Constants
::UTF8_REPLACEMENT
) !== false ) {
334 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
335 throw new MalformedTitleException( 'title-invalid-utf8', $text );
338 $parts['dbkey'] = $dbkey;
340 # Initial colon indicates main namespace rather than specified default
341 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
342 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
343 $parts['namespace'] = NS_MAIN
;
344 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
345 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
348 if ( $dbkey == '' ) {
349 throw new MalformedTitleException( 'title-invalid-empty', $text );
352 # Namespace or interwiki prefix
353 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
356 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
358 $ns = $this->language
->getNsIndex( $p );
359 if ( $ns !== false ) {
362 $parts['namespace'] = $ns;
363 # For Talk:X pages, check if X has a "namespace" prefix
364 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
365 if ( $this->language
->getNsIndex( $x[1] ) ) {
366 # Disallow Talk:File:x type titles...
367 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
368 } elseif ( $this->interwikiLookup
->isValidInterwiki( $x[1] ) ) {
369 # Disallow Talk:Interwiki:x type titles...
370 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
373 } elseif ( $this->interwikiLookup
->isValidInterwiki( $p ) ) {
376 $parts['interwiki'] = $this->language
->lc( $p );
378 # Redundant interwiki prefix to the local wiki
379 foreach ( $this->localInterwikis
as $localIW ) {
380 if ( strcasecmp( $parts['interwiki'], $localIW ) == 0 ) {
381 if ( $dbkey == '' ) {
382 # Empty self-links should point to the Main Page, to ensure
383 # compatibility with cross-wiki transclusions and the like.
384 $mainPage = Title
::newMainPage();
386 'interwiki' => $mainPage->getInterwiki(),
387 'local_interwiki' => true,
388 'fragment' => $mainPage->getFragment(),
389 'namespace' => $mainPage->getNamespace(),
390 'dbkey' => $mainPage->getDBkey(),
391 'user_case_dbkey' => $mainPage->getUserCaseDBKey()
394 $parts['interwiki'] = '';
395 # local interwikis should behave like initial-colon links
396 $parts['local_interwiki'] = true;
398 # Do another namespace split...
403 # If there's an initial colon after the interwiki, that also
404 # resets the default namespace
405 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
406 $parts['namespace'] = NS_MAIN
;
407 $dbkey = substr( $dbkey, 1 );
408 $dbkey = trim( $dbkey, '_' );
411 # If there's no recognized interwiki or namespace,
412 # then let the colon expression be part of the title.
417 $fragment = strstr( $dbkey, '#' );
418 if ( $fragment !== false ) {
419 $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
420 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
421 # remove whitespace again: prevents "Foo_bar_#"
422 # becoming "Foo_bar_"
423 $dbkey = preg_replace( '/_*$/', '', $dbkey );
426 # Reject illegal characters.
427 $rxTc = self
::getTitleInvalidRegex();
429 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
430 throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
433 # Pages with "/./" or "/../" appearing in the URLs will often be un-
434 # reachable due to the way web browsers deal with 'relative' URLs.
435 # Also, they conflict with subpage syntax. Forbid them explicitly.
437 strpos( $dbkey, '.' ) !== false &&
439 $dbkey === '.' ||
$dbkey === '..' ||
440 strpos( $dbkey, './' ) === 0 ||
441 strpos( $dbkey, '../' ) === 0 ||
442 strpos( $dbkey, '/./' ) !== false ||
443 strpos( $dbkey, '/../' ) !== false ||
444 substr( $dbkey, -2 ) == '/.' ||
445 substr( $dbkey, -3 ) == '/..'
448 throw new MalformedTitleException( 'title-invalid-relative', $text );
451 # Magic tilde sequences? Nu-uh!
452 if ( strpos( $dbkey, '~~~' ) !== false ) {
453 throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
456 # Limit the size of titles to 255 bytes. This is typically the size of the
457 # underlying database field. We make an exception for special pages, which
458 # don't need to be stored in the database, and may edge over 255 bytes due
459 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
460 $maxLength = ( $parts['namespace'] != NS_SPECIAL
) ?
255 : 512;
461 if ( strlen( $dbkey ) > $maxLength ) {
462 throw new MalformedTitleException( 'title-invalid-too-long', $text,
463 [ Message
::numParam( $maxLength ) ] );
466 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
467 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
468 # other site might be case-sensitive.
469 $parts['user_case_dbkey'] = $dbkey;
470 if ( $parts['interwiki'] === '' ) {
471 $dbkey = Title
::capitalize( $dbkey, $parts['namespace'] );
474 # Can't make a link to a namespace alone... "empty" local links can only be
475 # self-links with a fragment identifier.
476 if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] != NS_MAIN
) {
477 throw new MalformedTitleException( 'title-invalid-empty', $text );
480 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
481 // IP names are not allowed for accounts, and can only be referring to
482 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
483 // there are numerous ways to present the same IP. Having sp:contribs scan
484 // them all is silly and having some show the edits and others not is
485 // inconsistent. Same for talk/userpages. Keep them normalized instead.
486 if ( $parts['namespace'] == NS_USER ||
$parts['namespace'] == NS_USER_TALK
) {
487 $dbkey = IP
::sanitizeIP( $dbkey );
490 // Any remaining initial :s are illegal.
491 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
492 throw new MalformedTitleException( 'title-invalid-leading-colon', $text );
496 $parts['dbkey'] = $dbkey;
502 * Returns a simple regex that will match on characters and sequences invalid in titles.
503 * Note that this doesn't pick up many things that could be wrong with titles, but that
504 * replacing this regex with something valid will make many titles valid.
505 * Previously Title::getTitleInvalidRegex()
507 * @return string Regex string
510 public static function getTitleInvalidRegex() {
511 static $rxTc = false;
513 # Matching titles will be held as illegal.
515 # Any character not allowed is forbidden...
516 '[^' . Title
::legalChars() . ']' .
517 # URL percent encoding sequences interfere with the ability
518 # to round-trip titles -- you can't link to them consistently.
520 # XML/HTML character references produce similar issues.
521 '|&[A-Za-z0-9\x80-\xff]+;' .
523 '|&#x[0-9A-Fa-f]+;' .